package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.dto.*;
import com.sky.po.OrdersPO;
import com.sky.repository.OrderRepository;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Content:
 * @Author: Asen
 * @Date: 2023/9/11 15:31
 */
@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api(tags = "用户端订单相关接口")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private WebSocketServer webSocketServer;

    @PostMapping("/submit")
    @ApiOperation("用户下单")
    public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO source){
        return Result.success(orderService.submitOrder(source));
    }

    /**
     * 订单支付
     * @param source
     * @return
     * @throws Exception
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO source) throws Exception {
//        OrderPaymentVO orderPaymentVO = orderService.payment(ordersPaymentDTO);
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        //订单支付成功模拟
        OrdersPO ordersPO = orderRepository.selectOne(new LambdaQueryWrapper<OrdersPO>()
                .eq(OrdersPO::getNumber,source.getOrderNumber()));
        ordersPO.setStatus(OrdersPO.TO_BE_CONFIRMED);
        orderRepository.updateById(ordersPO);
        //提醒商家接单
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type",1);//1:来单提醒,2:客户催单
        map.put("orderId",ordersPO.getId());
        map.put("content","订单号"+source.getOrderNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
        return Result.success(orderPaymentVO);
    }

    @GetMapping("/historyOrders")
    @ApiOperation("查询订单")
    public Result<PageResult> historyOrders(OrdersPageQueryDTO source){
        return Result.success(orderService.conditionSearch(source));
    }

    @GetMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result repetition(@PathVariable Long id){
        orderService.repetition(id);
        return Result.success();
    }

    @GetMapping("/reminder/{id}")
    @ApiOperation("客户催单")
    public Result reminder(@PathVariable("id")Long id){
        orderService.reminder(id);
        return Result.success();
    }
}
